#include "stdafx.h"
#include "jappconfig.h"
#include <lua.hpp>
#include <wx/filename.h>
#include "lua_tinker.h"
#include <map>
#include "jglobals.h"
#include "strhelper.h"


static std::map<std::wstring,NetInfo*> sg_netInfoMap;
std::vector<std::unique_ptr<NetInfo>> g_infoList;
static std::wstring sg_connectionString;
static NetInfo * sg_curNetInfo=NULL;

static void RegNetInfo(const char* Name,const char* netAddr,const char* dbName,int port)
{
    std::unique_ptr<NetInfo> netInfo(new NetInfo);

    netInfo->name= utf2ws(Name);
    netInfo->netAddr=utf2ws(netAddr);
    netInfo->dbName=utf2ws(dbName);
    netInfo->port=port;
    if(sg_curNetInfo==NULL)
    {
        sg_curNetInfo=netInfo.get();
    }
    sg_netInfoMap[netInfo->name]=netInfo.get();
    g_infoList.push_back(std::move(netInfo));
}






JAppConfig::JAppConfig()
{



}

static const char sg_lua_funs[]=
u8R"(
函数 注册网络(tb)
    RegNetInfo(tb.名称,tb.IP地址,tb.数据库名,tb.端口)
结束
)";

bool JAppConfig::InitData()
{
    wxString  fileName=wxFileName::GetCwd()+ wxT("/config.lua");
    wxFile file(fileName,wxFile::read);
    if(file.IsOpened())
    {
        wxFileOffset len= file.Length();
        std::vector<char> data;
        data.resize(len+1,0);
        file.Read(data.data(),len);

        lua_State * L=luaL_newstate();
        luaL_openlibs(L);
        lua_tinker::init(L);
        lua_tinker::def(L,"RegNetInfo",&RegNetInfo);

        lua_tinker::dostring(L,std::string(sg_lua_funs));

        lua_tinker::dobuffer(L,data.data(),len);
        return !g_infoList.empty();
    }

    return false;
}

void JAppConfig::setCurNetInfo(const std::wstring &str)
{
    auto ptr=sg_netInfoMap.find(str);
    if(ptr!=sg_netInfoMap.end())
    {
        sg_curNetInfo=ptr->second;
    }
}

NetInfo *JAppConfig::getCurNetInfo()
{
    return sg_curNetInfo;
}

